package niu.toy.spring.mvc.impl.argument;

import cn.hutool.core.util.ReflectUtil;


import niu.toy.spring.ioc.annotation.Nullable;
import niu.toy.spring.mvc.HandlerArgumentResolver;
import niu.toy.spring.mvc.HandlerMethodParameter;
import niu.toy.spring.mvc.ModelAndViewContainer;
import niu.toy.spring.mvc.NativeWebRequest;
import niu.toy.spring.mvc.annotation.RequestBody;
import niu.toy.spring.support.BeanWrapper;
import niu.toy.spring.support.impl.BeanWrapperImpl;
import niu.toy.spring.util.WebUtil;


import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class RequestModelParamArgumentResolver implements HandlerArgumentResolver {
    @Override
    public boolean supportsParameter(HandlerMethodParameter parameter) {
       return !parameter.hasParameterAnnotation(RequestBody.class)&&!HandlerArgumentResolver.isSimpleProperty(parameter.getParameterType());
    }

    @Override
    @Nullable
    public final Object resolveArgument(HandlerMethodParameter parameter, NativeWebRequest request, ModelAndViewContainer mavContainer) throws Exception {
        Map<String, Object> params= WebUtil.getParametersStartingWith((HttpServletRequest)request.getNativeRequest(),null);

        Object bean= ReflectUtil.newInstance(parameter.getParameterType());
        BeanWrapper wrapper = new BeanWrapperImpl(bean);
        for(Map.Entry<String,Object> entry: params.entrySet()){
            wrapper.setPropertyValue(entry.getKey(),entry.getValue());
        }
        return bean;
    }




}
